import matplotlib
import numpy as np
import cv2
import matplotlib.pyplot as plt
matplotlib.use('TkAgg')
def gray_world(image):
    # 计算 RGB 三个通道的平均值
    means = np.mean(image, axis=(0, 1))
    # 计算平均灰度值
    gray_mean = np.mean(means)
    # 计算每个通道的缩放因子
    scale_factors = gray_mean / means
    # 对每个通道进行缩放
    corrected_image = np.clip(image * scale_factors, 0, 255).astype(np.uint8)
    return corrected_image


# 读取图像
image = cv2.imread('photo3.png')
# 转换为 RGB 格式
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# 应用灰度世界算法进行色彩校正
corrected_image = gray_world(image)

# 显示原始图像和校正后的图像
plt.subplot(121), plt.imshow(image)
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(corrected_image)
plt.title('Corrected Image'), plt.xticks([]), plt.yticks([])
plt.show()
